import 'dart:convert';
import 'package:http/http.dart' as http;

/*
http: ^1.2.2
* */

class Http {
  // GET 请求
  static Future<http.Response> get(String url, {Map<String, String>? header, Map<String, String>? params}) async {
    try {
      var h = {'Accept': 'application/json', 'Accept-Charset': 'utf-8'};
      if (header != null) {
        h.addAll(header);
      }
      var uri = Uri.parse(url);
      if (params != null) {
        uri = uri.replace(queryParameters: params);
      }
      final response = await http.get(uri, headers: h);
      return response;
    } catch (e) {
      throw Exception('[B]$url $params $e');
    }
  }

  // POST 请求
  static Future<http.Response> post(String url, {Map<String, dynamic>? data, Map<String, String>? header}) async {
    try {
      var h = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Accept-Charset': 'utf-8'};
      if (header != null) {
        h.addAll(header);
      }
      final response = await http.post(
        Uri.parse(url),
        headers: h,
        body: data != null ? json.encode(data) : "",
      );
      return response;
    } catch (e) {
      throw Exception('[B]$url $data $e');
    }
  }

  // PUT 请求
  static Future<http.Response> put(String url, {Map<String, dynamic>? data, Map<String, String>? header}) async {
    try {
      var h = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Accept-Charset': 'utf-8'};
      if (header != null) {
        h.addAll(header);
      }
      final response = await http.put(
        Uri.parse(url),
        headers: h,
        body: data != null ? json.encode(data) : "",
      );
      return response;
    } catch (e) {
      throw Exception('[B]$url $data $e');
    }
  }
}
